<template>
  <div>
    <div class="loginPart">
      <el-input v-model="searchName" placeholder="Search by name" type="text" style="width: 240px" clearable  :suffix-icon="Search"/>
      <div class="table-container">
        <table>
          <thead>
          <tr>
            <th>Name</th>
            <th>Address</th>
            <th>Phone</th>
            <th>Email</th>
            <th>Age</th>
            <th>Gender</th>
            <th>Action</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="(item, index) in numberedFilteredList" :key="index">
            <td v-if="!item.isEditing">{{ item.name }}</td>
            <td v-if="item.isEditing"><input v-model="item.user.name" type="text" /></td>
            <td v-if="!item.isEditing">{{ item.addr }}</td>
            <td v-if="item.isEditing"><input v-model="item.user.addr" type="text" /></td>
            <td v-if="!item.isEditing">{{ item.phone }}</td>
            <td v-if="item.isEditing"><input v-model="item.user.phone" type="text" /></td>
            <td v-if="!item.isEditing">{{ item.email }}</td>
            <td v-if="item.isEditing"><input v-model="item.user.email" type="text" /></td>
            <td v-if="!item.isEditing">{{ item.age }}</td>
            <td v-if="item.isEditing"><input v-model.number="item.user.age" type="number" /></td>
            <td v-if="!item.isEditing">{{ item.gender }}</td>
            <td v-if="item.isEditing">
              <select v-model="item.user.gender">
                <option value="male">Male</option>
                <option value="female">Female</option>
                <option value="other">Other</option>
              </select>
            </td>
            <td>
              <el-button type="primary" :icon="Edit" v-if="!item.isEditing" @click="toggleEditMode(index)" >编辑</el-button>
              <el-button type="success"  v-if="item.isEditing" @click="saveChanges(index)">
                保存<el-icon class="el-icon--right"><Upload /></el-icon>
              </el-button>
              <el-button type="danger" :icon="Delete" @click="deleteItem(index)" >删除</el-button>
            </td>
          </tr>
          </tbody>
        </table>
      </div>

    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { modifyWhiteList, showWhiteList,deleteWhiteList } from "@/api/InforManage";
import {Delete, Edit, Search} from "@element-plus/icons-vue";

const list = ref([]);

const fetchData = async () => {
  try {
    const response = await showWhiteList();
    list.value = response.data.list.map(item => ({
      ...item,
      user: reactive({
        name: item.name,
        addr: item.addr,
        phone: item.phone,
        email: item.email,
        age: item.age,
        gender: item.gender,
      }),
    }));
  } catch (error) {
    console.error(error);
  }
};

const searchInput = ref("");
fetchData();

const filteredUsers = computed(() => {
  return list.value.filter(user => user.fields.userName.includes(searchInput.value));
});

const searchName = ref("");
const filteredList = computed(() => {
  if (searchName.value === "") {
    return list.value;
  } else {
    return list.value.filter(item =>
        item.name.toLowerCase().includes(searchName.value.toLowerCase())
    );
  }
});

const numberedFilteredList = computed(() => {
  return filteredList.value.map((item, index) => ({
    ...item,
    index: index + 1,
  }));
});

function toggleEditMode(index) {
  list.value[index].isEditing = !list.value[index].isEditing;
}

function saveChanges(index) {
  const item = list.value[index];
  const requestData = {
    name: item.user.name,
    addr: item.user.addr,
    phone: item.user.phone,
    email: item.user.email,
    age: item.user.age,
    gender: item.user.gender,
  };

  // Update the item object with the edited data
  Object.assign(item, item.user);

  item.isEditing = false;

  modifyWhiteList(requestData)  // pass requestData object instead of function
      .then((response) => {
        console.log(requestData)
        var res = response.data
        if (res.respCode === '000000') {
          ElMessage.success('修改成功');
          fetchData();
        } else {
          ElMessage.error(res.respMsg);
        }
      })
      .catch((error) => {
        console.error(error);
        ElMessage.error('修改失败，请重试');
      });

  console.log(item);
}


function deleteItem(index) {

  console.log(list.value[index])

  const item = list.value[index];

  const requestData = {

    name: item.user.name

  };

  // Update the item object with the edited data
  Object.assign(item, item.user.name);

  deleteWhiteList(requestData)  // pass requestData object instead of function
      .then((response) => {
        console.log(requestData)
        var res = response.data
        if (res.respCode === '000000') {
          ElMessage.success('删除成功');
          fetchData();
        } else {
          ElMessage.error(res.respMsg);
        }
      })
      .catch((error) => {
        console.error(error);
        ElMessage.error('删除失败，请重试');
      });


  list.value.splice(index, 1);
}
</script>


<style scoped>
.loginPart {
  width: 90%;
  height: 650px;
  margin: 20px auto;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
  overflow-y: scroll;
}


table {
  width: 100%;
  border-collapse: collapse;
  background-color: #f2f2f2;
}

th,
td {
  padding: 10px;
  text-align: left;
}

th {
  background-color: #3c5287;
  color: white;
}

td input[type="text"],
td input[type="number"],
td select {
  width: 100%;
  padding: 5px;
  border: none;
  border-radius: 3px;
  background-color: white;
}

td input[type="text"]:disabled,
td input[type="number"]:disabled,
td select:disabled {
  background-color: #f2f2f2;
}

.table-container {
  margin-top: 15px;
}
</style>